import os
import webbrowser
from tkinter import filedialog, messagebox
from tkinter import scrolledtext

import ttkbootstrap as ttk
from PyPDF2 import PdfMerger
from ttkbootstrap.constants import *


class PDFMergePage(ttk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.pdf_files = []
        self.setup_ui()

    def setup_ui(self):
        # 创建上传按钮
        upload_frame = ttk.Frame(self)
        upload_frame.pack(fill=X, pady=10)

        self.upload_btn = ttk.Button(
            upload_frame,
            text="上传PDF",
            command=self.upload_pdf,
            style="primary.TButton"
        )
        self.upload_btn.pack(side=LEFT, padx=5)

        # 显示已上传文件列表
        self.file_list_frame = ttk.Frame(self)
        self.file_list_frame.pack(fill=BOTH, expand=YES, padx=10, pady=10)

        # 文件列表和预览区域
        self.file_list = scrolledtext.ScrolledText(
            self,
            width=50,
            height=10,
            wrap=ttk.WORD
        )
        self.file_list.pack(padx=5, pady=5, fill=BOTH, expand=YES)
        self.file_list.config(state=DISABLED)

        # 预览区域
        self.preview_frame = ttk.Frame(self.file_list_frame)
        self.preview_frame.pack(side=RIGHT, fill=BOTH, expand=YES, padx=5)

        # 合并按钮
        self.merge_btn = ttk.Button(
            self,
            text="开始合并",
            command=self.merge_pdfs,
            style="success.TButton"
        )
        self.merge_btn.pack(pady=10)

        # 进度条
        self.progress = ttk.Progressbar(
            self,
            mode='determinate',
            length=300
        )
        self.progress.pack(pady=10)

        # 导出文件信息
        self.export_frame = ttk.LabelFrame(self, text="导出文件")
        self.export_frame.pack(fill=X, padx=10, pady=10)

        self.export_path_label = ttk.Label(self.export_frame, text="未导出文件")
        self.export_path_label.pack(side=LEFT, padx=5)

        self.preview_export_btn = ttk.Button(
            self.export_frame,
            text="预览",
            command=self.preview_export,
            style="info.TButton",
            state=DISABLED
        )
        self.preview_export_btn.pack(side=LEFT, padx=5)

    def upload_pdf(self):
        file_paths = filedialog.askopenfilenames(
            filetypes=[("PDF文件", "*.pdf")]
        )
        if file_paths:
            self.pdf_files.extend(file_paths)
            self.update_file_list()

    def update_file_list(self):
        self.file_list.config(state=NORMAL)
        self.file_list.delete(1.0, ttk.END)

        for i, file_path in enumerate(self.pdf_files, 1):
            self.file_list.insert(ttk.END, f"{i}. {os.path.basename(file_path)}\n")

            # 添加操作按钮
            btn_frame = ttk.Frame(self.file_list)
            self.file_list.window_create(ttk.END, window=btn_frame)

            # 预览按钮
            preview_btn = ttk.Button(
                btn_frame,
                text="预览",
                command=lambda path=file_path: self.preview_pdf(path),
                style="info.TButton",
                width=5
            )
            preview_btn.pack(side=LEFT, padx=2)

            # 删除按钮
            delete_btn = ttk.Button(
                btn_frame,
                text="删除",
                command=lambda idx=i - 1: self.delete_pdf(idx),
                style="danger.TButton",
                width=5
            )
            delete_btn.pack(side=LEFT, padx=2)

            # 上移按钮
            if i > 1:
                up_btn = ttk.Button(
                    btn_frame,
                    text="↑",
                    command=lambda idx=i - 1: self.move_pdf(idx, -1),
                    style="primary.TButton",
                    width=2
                )
                up_btn.pack(side=LEFT, padx=2)

            # 下移按钮
            if i < len(self.pdf_files):
                down_btn = ttk.Button(
                    btn_frame,
                    text="↓",
                    command=lambda idx=i - 1: self.move_pdf(idx, 1),
                    style="primary.TButton",
                    width=2
                )
                down_btn.pack(side=LEFT, padx=2)

            self.file_list.insert(ttk.END, "\n")

        self.file_list.config(state=DISABLED)

    def preview_pdf(self, file_path):
        try:
            webbrowser.open(file_path)
        except Exception as e:
            messagebox.showerror("错误", f"预览失败：{str(e)}")

    def delete_pdf(self, index):
        del self.pdf_files[index]
        self.update_file_list()

    def move_pdf(self, index, direction):
        if 0 <= index + direction < len(self.pdf_files):
            self.pdf_files[index], self.pdf_files[index + direction] = \
                self.pdf_files[index + direction], self.pdf_files[index]
            self.update_file_list()

    def merge_pdfs(self):
        if not self.pdf_files:
            messagebox.showerror("错误", "请先上传PDF文件")
            return

        # 获取第一个PDF的文件名作为默认输出文件名
        default_name = os.path.splitext(os.path.basename(self.pdf_files[0]))[0] + "_merged.pdf"

        output_path = filedialog.asksaveasfilename(
            defaultextension=".pdf",
            filetypes=[("PDF文件", "*.pdf")],
            initialfile=default_name
        )

        if not output_path:
            return

        # 检查文件是否存在
        if os.path.exists(output_path):
            if not messagebox.askyesno("确认", "文件已存在，是否覆盖？"):
                return

        try:
            self.progress['value'] = 0
            self.update_idletasks()

            merger = PdfMerger()

            # 添加文件到合并器
            for i, pdf_file in enumerate(self.pdf_files):
                merger.append(pdf_file)
                # 更新进度
                progress = (i + 1) / len(self.pdf_files) * 100
                self.progress['value'] = progress
                self.update_idletasks()

            # 设置PDF标题
            title = os.path.splitext(os.path.basename(output_path))[0]
            merger.add_metadata({'/Title': title})

            # 保存合并后的文件
            merger.write(output_path)
            merger.close()

            self.progress['value'] = 100
            self.update_idletasks()

            # 更新导出文件信息
            self.export_path_label.config(text=output_path)
            self.preview_export_btn.config(state=NORMAL)

            messagebox.showinfo("成功", "PDF文件已合并并保存")

        except Exception as e:
            messagebox.showerror("错误", f"合并失败：{str(e)}")
        finally:
            self.progress['value'] = 0

    def preview_export(self):
        try:
            webbrowser.open(self.export_path_label.cget("text"))
        except Exception as e:
            messagebox.showerror("错误", f"预览失败：{str(e)}")
